import { LOGIN, LOGOUT } from './actionTypes.js'
let defaultState = {
  userInfo: {},
  token:'',
  role:''
}
// 初始 刷新时 取缓存 赋值 给 state  存的名字就是 user
const storageState = localStorage.getItem('user')
                      ?JSON.parse(localStorage.getItem('user'))
                       :null;

if(storageState){
  defaultState = storageState
}

const reducer = (state=defaultState, action)=>{
  let newState = JSON.parse(JSON.stringify(state))
  switch (action.type){
    case LOGIN:
      newState.userInfo = action.value.userInfo
      newState.token = action.value.token
      newState.role = action.value.role
      break;
    case LOGOUT: // 退出登录
      newState.userInfo = {}
      newState.token = ""
      newState.role = ""
      // 去除本地缓存
      localStorage.removeItem('userInfo');
      localStorage.removeItem('role');
      localStorage.removeItem('token');
      break;
    default:
      break;
  }
  // 同步  缓存
  localStorage.setItem('user', JSON.stringify(newState))
  return newState
}

export default reducer